import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { ChatService } from '../services/chat.service';

interface Message {
  id: string;
  text: string;
  isBot: boolean;
  timestamp: number;
}

interface ChatHistory {
  [serviceId: string]: Message[];
}

interface ChatStore {
  histories: ChatHistory;
  currentService: string;
  isLoading: boolean;
  error: string | null;
  setCurrentService: (serviceId: string) => void;
  addMessage: (text: string, isBot: boolean) => void;
  sendMessage: (text: string, systemPrompt: string) => Promise<void>;
  setError: (error: string | null) => void;
  clearHistory: (serviceId: string) => void;
}

export const useChatStore = create<ChatStore>()(
  persist(
    (set, get) => ({
      histories: {},
      currentService: 'default',
      isLoading: false,
      error: null,

      setCurrentService: (serviceId: string) => {
        set({ currentService: serviceId });
      },

      setError: (error) => set({ error }),

      addMessage: (text: string, isBot: boolean) => {
        const { currentService } = get();
        const newMessage = {
          id: Date.now().toString(),
          text,
          isBot,
          timestamp: Date.now(),
        };

        set(state => ({
          histories: {
            ...state.histories,
            [currentService]: [
              ...(state.histories[currentService] || []),
              newMessage,
            ],
          },
        }));
      },

      clearHistory: (serviceId: string) => {
        set(state => ({
          histories: {
            ...state.histories,
            [serviceId]: [],
          },
        }));
      },

      sendMessage: async (text: string, systemPrompt: string) => {
        const { addMessage, setError } = get();
        
        addMessage(text, false);
        set({ isLoading: true, error: null });

        try {
          const reply = await ChatService.sendMessage(text, systemPrompt);
          if (reply) {
            addMessage(reply, true);
          } else {
            throw new Error('No response from AI');
          }
        } catch (error) {
          console.error('Error sending message:', error);
          setError(error instanceof Error ? error.message : '发生未知错误');
          addMessage("抱歉，发生了一些错误。请稍后再试。", true);
        } finally {
          set({ isLoading: false });
        }
      },
    }),
    {
      name: 'chat-storage',
      partialize: (state) => ({
        histories: state.histories,
      }),
    }
  )
);